package com.hs.srm.admin.modules.summary.controller;


import com.alibaba.fastjson.JSONArray;
import com.hs.srm.admin.common.util.ExcelUtil;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.summary.entity.VendorSummaryEntity;
import com.hs.srm.admin.modules.summary.service.VendorSummaryService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sunnykid.file.FileException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/vendorSummary")
public class VendorSummaryController extends AbstractController {
    @Autowired
    private VendorSummaryService vendorSummaryService;
    @Autowired
    private ScmPoItemService scmPoItemService;
    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        PageUtils pu = this.vendorSummaryService.selectDetailPage(params);
        List<VendorSummaryEntity> list = (List<VendorSummaryEntity>) pu.getList();
        calculatePercentage(list);
        return R.ok(pu);
    }


    /**
     * 计算百分比
     */
    private void calculatePercentage(List<VendorSummaryEntity> list) {
        BigDecimal allTotalPrice = this.vendorSummaryService.selectAllTatolPrice();
        BigDecimal allTotalPoCount = this.vendorSummaryService.selectAllpoCounts();
        BigDecimal ordersPercentage = null;
        BigDecimal pricePercentage = null;
        for (VendorSummaryEntity vendorSummaryEntity : list) {
            BigDecimal totalPrice = vendorSummaryEntity.getOrderTotalPrice();
            BigDecimal orderTotalNumber = vendorSummaryEntity.getOrderTotalNumber();
            if (totalPrice != null && allTotalPoCount != null) {
                pricePercentage = totalPrice.divide(allTotalPrice, 5, RoundingMode.HALF_UP);
                ordersPercentage = orderTotalNumber.divide(allTotalPoCount, 5, RoundingMode.HALF_UP);
                vendorSummaryEntity.setPricePercentage(pricePercentage);
                vendorSummaryEntity.setOrdersPercentage(ordersPercentage);
            }

        }
    }


    /**
     * 下载文件
     */
    public boolean download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setHeader("content-type", "application/x-gzip");
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 导出excel表
     *
     * @param vendorId
     * @return
     */
    @RequestMapping("/export")
    public void export(@RequestParam("vendorId") String vendorId, @RequestParam("rowNo") String rowNo, HttpServletResponse response) throws FileException, IOException {
        String[] vendorIds = vendorId.split(",");
        String[] rowNos = rowNo.split(",");
        List<VendorSummaryEntity> vendorSummaryEntities = this.vendorSummaryService.selectByConditions(vendorIds);
        calculatePercentage(vendorSummaryEntities);
        JSONArray studentArray = new JSONArray();
        for (VendorSummaryEntity vendorSummaryEntity : vendorSummaryEntities) {
            studentArray.add(vendorSummaryEntity);
        }

        //titleList存放了2个元素,分别为titleMap和headMap
        ArrayList<LinkedHashMap> titleList = new ArrayList<LinkedHashMap>();
        // 1.titleMap存放了该excel的头信息
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>();
        titleMap.put("title1", "供应商排名");
        titleMap.put("title2", "");
        // 2.headMap存放了该excel的列项
        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("vendorId", "供应商代码");
        headMap.put("vendorName", "供应商名称");
        headMap.put("orderTotalPrice", "订单总价值");
        headMap.put("pricePercentage", "订单金额所占的百分比");
        headMap.put("orderTotalNumber", "订单总数量");
        headMap.put("ordersPercentage", "订单总数量所占的百分比");
        titleList.add(titleMap);
        titleList.add(headMap);
        String pathtem = SysConfig.getUploadPath() + File.separator;
        File file = new File(pathtem);
        if (!file.exists()) {
            file.mkdirs();// 创建该文件夹目录
        }
        OutputStream os = null;
        String Path = "";
        try {
            long start = System.currentTimeMillis();
            // .xlsx格式
            Path = file.getAbsolutePath() + File.separator + start + ".xlsx";
            os = new FileOutputStream(file.getAbsolutePath() + File.separator + start + ".xlsx");
            ExcelUtil.exportExcel(titleList, studentArray, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            os.close();
        }
        if (!"".equals(Path)) {
            boolean b = download(Path, response);
            if (b) {
                ExcelUtil.delete(file);
            }
        }

    }
}
